package net.easyjava.framework.web.security;

import net.easyjava.tools.security.aes.AESTools;
import net.easyjava.tools.security.md5.Md5Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wxnacy on 15/12/22.
 */
public abstract class UserSecurity {
    protected static Logger logger = LoggerFactory.getLogger(UserSecurity.class);




    protected static final String AES_KEY = "5c948342a88fb378467a1eb8a7afd485";
    protected static final String SIGN_KEY = "3b7bcc0448703bd5abde58a2aa3fa7c6";

    protected final AESTools aesTools;

    public UserSecurity() {
        super();
        this.aesTools = new AESTools(this.AES_KEY);
    }

    /**
     * 获取加密中的用户信息
     * @param request
     * @return
     */
    public UserSecurityBean getUserSecurityBean(HttpServletRequest request){
        String userSecurity = this.readUserSecurity(request);
        if(userSecurity == null){
            logger.info("request 中没有用户");
            return null;
        }

        //将信息加密
        try {
            userSecurity = this.aesTools.decrypt(userSecurity);
            UserSecurityBean userSecurityBean = new UserSecurityBean(userSecurity);

            userSecurity = this.aesTools.encrypt(userSecurityBean.toSecurityString());
            if (userSecurityBean.getSign().equalsIgnoreCase(Md5Tools.md5(userSecurity+SIGN_KEY))){
                return userSecurityBean;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
        }

        return null;
    }

    /**
     * 将用户信息加密保存
     * @param response
     */
    protected void setUserSecurityBean(HttpServletResponse response,String userId,String userIp,long maxAge){
        UserSecurityBean userSecurityBean = new UserSecurityBean(userId,userIp,maxAge);
        try {
            //将信息加密
            String userSecurity = this.aesTools.encrypt(userSecurityBean.toSecurityString());

            //生成sign
            String userSecuritySign = Md5Tools.md5(userSecurity + SIGN_KEY);
            //二次加密
            userSecurity = this.aesTools.encrypt(userSecurityBean.toSecuritySignString(userSecuritySign));

            this.writeUserSecurity(response,userSecurity,maxAge);
        } catch (Exception e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
        }
    }

    public abstract void setLongUserSecurityBean(HttpServletResponse response,String userId,String userIp);

    public abstract void setShortUserSecurityBean(HttpServletResponse response,String userId,String userIp,long maxAge);

    protected abstract void writeUserSecurity(HttpServletResponse response,String value,long maxAge);

    public abstract void removeUserSecurity(HttpServletRequest request,HttpServletResponse response);


    protected abstract String readUserSecurity(HttpServletRequest request);


}
